<template>
  <div class="class-container">
    <div class="header-actions">
      <el-button type="primary" @click="handleAdd">新增</el-button>
      <el-button
        type="danger"
        :disabled="!multipleSelection.length"
        @click="handleBatchDelete"
        >批量删除</el-button
      >
    </div>

    <el-table
      v-loading="loading"
      :data="classList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="序号" type="index" width="80" />
      <el-table-column prop="classNo" label="班级号" />
      <el-table-column prop="teacherFullName" label="班主任" />
      <el-table-column prop="mayjorName" label="所属专业" />
      <el-table-column prop="enrollmentYear" label="入学年份" width="100" />
      <el-table-column prop="studentCount" label="学生数量" width="100" />
      <el-table-column label="创建时间" width="180">
        <template #default="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="280">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button
            type="info"
            size="small"
            @click="handleViewStudents(scope.row)"
          >
            查看学生
          </el-button>
          <el-button
            type="danger"
            size="small"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.pageNum"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 班级表单对话框 -->
    <class-form
      v-if="formVisible"
      v-model="formVisible"
      :form-type="formType"
      :class-data="currentClass"
      @submit-success="fetchClassList"
    />

    <!-- 查看班级学生对话框 -->
    <el-dialog
      v-model="studentsDialogVisible"
      title="班级学生列表"
      width="800px"
    >
      <div v-if="classStudents.length === 0" class="empty-data">
        <p>该班级暂无学生</p>
      </div>
      <el-table v-else :data="classStudents" style="width: 100%">
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column prop="studentNo" label="学号" />
        <el-table-column prop="fullName" label="姓名" />
        <el-table-column prop="sexText" label="性别" width="80" />
        <el-table-column prop="phoneNumber" label="电话号码" />
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
          :formatter="(row) => formatDateTime(row.createTime)"
        />
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="studentsDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import classApi from "@/api/class";
import ClassForm from "./components/ClassForm.vue";

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return "";
  const date = new Date(dateTime);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
};

// 数据加载状态
const loading = ref(false);
// 班级列表数据
const classList = ref([]);
// 选中的班级列表（用于批量操作）
const multipleSelection = ref([]);
// 分页参数
const pagination = ref({
  pageNum: 1,
  pageSize: 10,
  total: 0,
});
// 表单对话框可见性
const formVisible = ref(false);

// 表单类型（add/edit）
const formType = ref("");
// 当前操作的班级数据
const currentClass = ref({});

// 学生列表对话框可见性
const studentsDialogVisible = ref(false);
// 当前班级的学生列表
const classStudents = ref([]);

// 获取班级列表
const fetchClassList = async () => {
  loading.value = true;
  try {
    const response = await classApi.getClassList(
      pagination.value.pageNum,
      pagination.value.pageSize
    );

    classList.value = response.list || [];
    pagination.value.total = response.total || 0;
  } catch (error) {
    console.error("获取班级列表失败:", error);
    ElMessage.error("获取班级列表失败");
  } finally {
    loading.value = false;
  }
};

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  multipleSelection.value = selection;
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.value.pageSize = size;
  pagination.value.pageNum = 1; // 重置为第一页
  fetchClassList();
};

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.value.pageNum = page;
  fetchClassList();
};

// 添加班级
const handleAdd = () => {
  currentClass.value = {}; // 清空当前班级数据
  formType.value = "add";
  formVisible.value = true;
};

// 编辑班级
const handleEdit = (row) => {
  currentClass.value = { ...row }; // 复制班级数据
  formType.value = "edit";
  formVisible.value = true;
};

// 删除班级
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除班级"${row.classNo}"吗？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        await classApi.deleteClass(row.id);
        ElMessage.success("删除成功");
        fetchClassList(); // 刷新列表
      } catch (error) {
        console.error("删除班级失败:", error);
        ElMessage.error("删除班级失败");
      }
    })
    .catch(() => {
      // 取消删除，不做处理
    });
};

// 批量删除班级
const handleBatchDelete = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning("请选择要删除的班级");
    return;
  }

  const classNames = multipleSelection.value
    .map((item) => item.classNo)
    .join("、");
  ElMessageBox.confirm(
    `确定要删除选中的${multipleSelection.value.length}个班级(${classNames})吗？`,
    "提示",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }
  )
    .then(async () => {
      try {
        // 循环删除选中的班级
        const promises = multipleSelection.value.map((item) =>
          classApi.deleteClass(item.id)
        );
        await Promise.all(promises);
        ElMessage.success("批量删除成功");
        fetchClassList(); // 刷新列表
      } catch (error) {
        console.error("批量删除班级失败:", error);
        ElMessage.error("批量删除班级失败");
      }
    })
    .catch(() => {
      // 取消删除，不做处理
    });
};

// 查看班级学生
const handleViewStudents = async (row) => {
  try {
    const response = await classApi.getClassStudents(row.id);
    classStudents.value = response || [];
    studentsDialogVisible.value = true;
  } catch (error) {
    console.error("获取班级学生列表失败:", error);
    ElMessage.error("获取班级学生列表失败");
  }
};

// 页面加载时获取班级列表
onMounted(() => {
  fetchClassList();
});
</script>

<style scoped>
.class-container {
  padding: 20px;
}

.header-actions {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.empty-data {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style>
